<template>
  <div class="bottom-view">
    <dv-border-box-8>
      <el-card shadow="hover" class="view">
        <template #header>
          <div>关键词搜索</div>
        </template>
        <div class="search-view">
          <div class="chart-wrap">
            <div class="chart">
              <div class="title">搜索用户数</div>
              <div class="count">
                {{ numberFormat(lineChartData.totalUsers) }}
              </div>
              <v-chart
                :option="getLineOption('userList', '搜索用户数')"
                autoresize
              ></v-chart>
            </div>
            <div class="chart">
              <div class="title">搜索量</div>
              <div class="count">
                {{ numberFormat(lineChartData.totalCount) }}
              </div>
              <v-chart
                :option="getLineOption('countList', '搜索量')"
                autoresize
              ></v-chart>
            </div>
          </div>
          <div class="search-table">
            <vxe-table
              :data="tablePageData"
              style="width: 100%"
              :header-row-style="{
                backgroundColor: '#11144e',
                color: 'white',
                fontFamily: 'YouSheBiaoTiHei',
              }"
              :row-style="{
                backgroundColor: '#11144e',
                color: 'white',
              }"
              size="small"
            >
              <vxe-column
                field="rankNo"
                title="排名"
                width="100"
                align="center"
              >
              </vxe-column>
              <vxe-column field="word" title="关键字"> </vxe-column>
              <vxe-column field="count" title="搜索数量"> </vxe-column>
              <vxe-column field="user" title="搜索用户数"> </vxe-column>
              <vxe-column field="range" title="搜索占比"> </vxe-column>
            </vxe-table>
            <el-pagination
              layout="prev, pager, next"
              :total="tableTotalData.length"
              v-model:current-page="current"
              :page-size="pageSize"
            />
          </div>
        </div>
      </el-card>
    </dv-border-box-8>
    <dv-border-box-8>
      <el-card shadow="hover" class="view">
        <template #header>
          <div>分类销售排行</div>
          <el-radio-group size="small" v-model="radioSelect">
            <el-radio-button label="品类">品类</el-radio-button>
            <el-radio-button label="商品">商品</el-radio-button>
          </el-radio-group>
        </template>
        <div class="search-view">
          <v-chart :option="getPieOption()" autoresize></v-chart>
        </div>
      </el-card>
    </dv-border-box-8>
  </div>
</template>

<script setup lang="ts">
// 引入动态线条
import { BorderBox8 as DvBorderBox8 } from "@kjgl77/datav-vue3";
import { computed, ref } from "vue";
import { useDataStore } from "@/stores/echartsData";
import useFormat from "@/hooks/useFormat";
// 实例化仓库
const dataStore = useDataStore();
// 数据格式化
const { numberFormat } = useFormat();
// 右侧分类切换
const radioSelect = ref<string>("品类");
const current = ref<number>(1);
const pageSize = ref<number>(5);

const searchWord = computed(() => dataStore.reportData.searchWord);
// 分类销售排行
const saleRank = computed(() => dataStore.reportData.saleRank);

// 表格所有数据
const tableTotalData = computed(() => {
  if (!searchWord.value) return [];
  return searchWord.value.map((item, index) => {
    return {
      ...item,
      rankNo: index + 1, // 排名
      range: ((item.user / item.count) * 100).toFixed(2) + "%", // 占比
    };
  });
});

// 表格分页数据
const tablePageData = computed(() => {
  return tableTotalData.value.slice(
    (current.value - 1) * pageSize.value,
    current.value * pageSize.value
  );
});

// 折线图数据
const lineChartData = computed(() => {
  const data = {
    wordList: [] as string[],
    userList: [] as number[],
    countList: [] as number[],
    totalUsers: 0, // 总用户数
    totalCount: 0, // 总搜索数
  };
  if (tableTotalData.value && tableTotalData.value.length > 0) {
    tableTotalData.value.forEach((item) => {
      data.wordList.push(item.word);
      data.userList.push(item.user);
      data.countList.push(item.count);
      data.totalUsers += item.user;
      data.totalCount += item.count;
    });
  }
  return data;
});

// 折线图配置
const getLineOption = (listname: "userList" | "countList", name: string) => {
  return {
    xAxis: {
      type: "category",
      boundaryGap: false, // 两侧不留空白
      data: lineChartData.value.wordList,
    },
    yAxis: {
      show: false,
    },
    series: [
      {
        name,
        data: lineChartData.value[listname],
        type: "line",
        symbol: "circle", // 默认是空心圆（中间是白色的），改成实心圆
        showSymbol: false,
        smooth: true,
        // 线条样式
        lineStyle: {
          width: 1,
          color: "#707070", // 线条颜色
          borderColor: "#707070",
        },
        areaStyle: {
          // 区域填充样式
          // 线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "#846B38", // 0% 处的颜色
              },
              {
                offset: 0.5,
                color: "#403E47", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "#11144E", // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },

          shadowColor: "rgba(255, 199, 37, 0)", // 阴影颜色
          shadowBlur: 20, // shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
        },
        emphasis: {
          scale: true,
        },
        itemStyle: {
          color: "#F5B348",
          shadowColor: "rgba(245, 179, 72, 0.3)",
          shadowBlur: 3,
        },
      },
    ],
    grid: {
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
    },

    tooltip: {
      trigger: "axis",
      confine: true,
      formatter: (params: any) => {
        let tipData = params[0];
        let html = `<div class="lineChart-bg">
                        <span style="">${tipData.name} <i >${tipData.value}</i> 人次</span>
                    </div>`;
        return html;
      },
      backgroundColor: "transparent", // 提示标签背景颜色
      borderColor: "transparent",
      axisPointer: {
        lineStyle: {
          type: "dashed",
        },
        snap: true,
      },
      extraCssText: "box-shadow: none;padding:0",
    },
  };
};

/** 右侧el-card **/
// 分类销售排行饼状图数据
const pieChartData = computed(() => {
  const data = {
    categoryList: [] as any[],
    cTotal: 0, // 品类总订单数
    goodsList: [] as any[],
    gTotal: 0, // 商品总订单数
  };

  if (saleRank.value) {
    // 整理数据模型
    const {
      category: { axisX, data: data1 },
      goods: { axisX: axisX2, data: data2 },
    } = saleRank.value;
    // console.log(data1);
    const total = data1.reduce((pre, item) => pre + item, 0); // data1是品类销售的数据 是number[]
    data.cTotal = total;

    axisX.forEach((item, index) => {
      // 该分类在总分类中的订单占比数
      const percent = ((data1[index] / total) * 100).toFixed(2) + "%";
      data.categoryList.push({
        name: item + "|" + percent,
        value: data1[index],
        percent,
        labelName: item,
      });
    });

    // 商品销售排行数据 同上
    const total2 = data2.reduce((pre, item) => pre + item, 0); // data2是商品销售的数据 是number[]
    data.gTotal = total2;
    axisX2.forEach((item, index) => {
      // 该商品在所有商品中的订单占比数
      const percent = ((data2[index] / total) * 100).toFixed(2) + "%";
      data.goodsList.push({
        name: item + "|" + percent,
        value: data2[index],
        percent,
        labelName: item,
      });
    });
  }
  return data;
});
// 饼状图配置
const getPieOption = () => {
  // 解构饼状图数据
  const { categoryList, cTotal, goodsList, gTotal } = pieChartData.value;
  // 表单数据切换
  const list = radioSelect.value === "品类" ? categoryList : goodsList;
  // 总订单数切换
  const total = radioSelect.value === "品类" ? cTotal : gTotal;
  return {
    // 饼状图标题
    title: [
      {
        text: `${radioSelect.value}分布`,
        textStyle: {
          fontSize: 18,
          fontWeight: "normal",
          color: "white",
          fontFamily: "YouSheBiaoTiHei",
        },
        left: 20,
        top: 20,
      },
      {
        text: "累计订单量",
        // 副标题文本
        subtext: total,
        textStyle: {
          fontSize: 14,
          color: "white",
        },
        // 副标题文字的颜色
        subtextStyle: {
          fontSize: 28,
          color: "white",
        },
        left: "34.5%",
        top: "42.5%",
        // 整体（包括 text 和 subtext）的水平对齐
        textAlign: "center",
      },
    ],
    // 提示
    tooltip: {
      trigger: "item",
      // 提示内容及样式
      formatter: (params: any) => {
        // data: 当前项数据
        // marker: 内置提供的圆点标签
        // console.log(params)
        return `${radioSelect.value}分布<br/>
                ${params.marker + params.data.labelName}<br/>
                ${params.marker}数量：${params.data.value}<br/>
                ${params.marker}占比：${params.data.percent}
`;
      },
    },
    legend: {
      // 图例列表的布局朝向
      orient: "vertical",
      // 图例组件离容器上侧的距离
      top: "middle",
      // 图例组件离容器左侧的距离
      left: "70%",
      textStyle: {
        color: "#fff",
        fontSize: "13px",
      },
    },
    series: [
      {
        name: `${radioSelect.value}分布`,
        type: "pie",
        // 中心点位置
        center: ["35%", "50%"],
        // 圆环半径
        radius: ["35%", "50%"],
        // 不用防止标签文本与图重叠(圆环图)
        // 是否启用防止标签重叠策略，默认开启，在标签拥挤重叠的情况下会挪动各个标签的位置，防止标签间的重叠。
        avoidLabelOverlap: false,
        // 高亮状态的扇区和标签样式
        // emphasis: {
        //   label: {
        //     show: true,
        //     fontSize: 40,
        //     fontWeight: "bold",
        //   },
        // },
        // 图表项的标题
        label: {
          // 在环的外侧
          position: "outside",
          // 指定特定标题
          formatter: function (params: any) {
            return params.data.labelName;
          },
          color: "white",
          fontWeight: "bold",
          fontSize: "13px",
        },
        // 标签的视觉引导线配置
        labelLine: {
          // 视觉引导线第一段的长度
          length: 7,
          // 视觉引导项第二段的长度
          length2: 5,
        },
        data: list,
      },
    ],
  };
};
</script>
<script lang="ts">
export default {
  name: "ButtonView",
};
</script>

<style lang="scss" scoped>
:deep(.el-pagination button) {
  color: white;
  background-color: rgba(255, 255, 255, 0);
}
:deep(.el-pager li) {
  color: white;
  background-color: rgba(255, 255, 255, 0);
}

:deep(.el-pager li.is-active) {
  color: #05e8fe;
}
.bottom-view {
  display: flex;
  // padding-bottom: 10px;

  .view {
    flex: 1;

    &:first-child {
      margin-right: 10px;
    }

    &:last-child {
      margin-left: 10px;
    }

    :deep(.el-card__header) {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 40px;
      font-size: 25px;
      font-family: YouSheBiaoTiHei;
    }

    :deep(.el-card__body) {
      padding-bottom: 0;
    }

    .search-view {
      height: 400px;
      display: flex;
      flex-direction: column;

      .chart-wrap {
        display: flex;

        .chart {
          flex: 1;

          &:first-child {
            margin-right: 5px;
          }

          &:last-child {
            margin-left: 5px;
          }

          .title {
            font-size: 18px;
            color: white;
            font-family: YouSheBiaoTiHei;
          }

          .count {
            font-size: 18px;
            color: white;
            font-family: MetroDF;
            font-weight: 500;
            letter-spacing: 2px;
            color: #05e8fe;
          }

          .echarts {
            margin-top: 10px;
            height: 40px;
          }
        }
      }

      .search-table {
        flex: 1;
        margin-top: 10px;

        .el-pagination {
          text-align: right;
          margin-top: 10px;
        }
      }
    }
  }
}
// 折线图提示样式修改
:deep(.lineChart-bg) {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  width: 180px;
  height: 60px;
  padding-left: 20px;
  background: url("../images/line-bg.png") no-repeat;
  background-size: 100% 100%;
  span {
    font-size: 12px;
    color: rgb(255 255 255 / 80%);
    i {
      font-style: normal;
      color: #f5b348;
    }
  }
}
</style>
